using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using BaseAmd.Mmt;
using Newtonsoft.Json;
using Catastrophe.AutoSulution.EDC;
using Catastrophe.Common;
using SiemensAmd.Mmt.Amd;
using SiemensAmd.Mmt.Amd.McisDbDal;
using SiemensAmd.Mmt.Amd.McisDbModel;
using SiemensAmd.Mmt.Amd.TdiToolDetailsJson;
using SiemensAmd.Mmt.McisDbDal;
using SiemensAmd.Mmt.McisDbModel;

namespace SiemensAmd.Mmt
{
	public class MmtToolManager
	{
		private const int ReadToolsInterval = 500;

		private Thread _tdRefreshMag;

		private Thread _tdToolSync;

		public Action<bool, string> DeleteToolHandler;

		public MmtHttpPost HttpPost;

		public Action<bool, string> LoadToolHandler;

		public Action<string> GetSendBackHandler;

		protected ToolDataDal ToolDataDal;

		protected TdiToolDataDal TdiToolDataDal;

		protected TdiToolPlaceDal TdiToolPlaceDal;

		protected TdiToolMasterDataDal TdiToolMasterDataDal;

		protected TdiToolDataDetailsDal TdiToolDataDetailDal;

		protected TrgToolDataDetailsDal TrgToolDataDetailsDal;

		private bool _getSendBackAbort = true;

		private Thread _tdGetSendBack;

		private bool _firstToolSync = true;

		public const string InsertOperate = "Insert";

		public const string UpdateOperate = "Update";

		public const string DeleteOperate = "Delete";

		public string AmdHost { get; set; }

		public string Certificate { get; set; }

		public string Name { get; set; }

		public string VersionInfo { get; set; }

		public string ServerNode { get; set; }

		public string DeviceNode { get; set; }

		public string DstMag { get; set; }

		public string PresetterMag { get; set; }

		public bool RefreshSucess { get; set; }

		public string RefreshResponse { get; set; }

		public string TrashMag { get; set; }

		public bool LoadFinished => false;

		public bool UnloadFinished => false;

		public List<MmtToolEntity> ToolMagEntites { get; set; } = new List<MmtToolEntity>();


		public List<ToolMagConfigEntity> MagConfig { get; set; }

		public List<string> EmptyPlaces { get; set; }

		public string DbUser { get; set; } = "sa";


		public string DbName { get; set; } = "MCISDB";


		public string DbPwd { get; set; } = "";


		public Func<Dictionary<string, List<MmtToolExEntity>>, bool> FirstToolSyncHandler { get; set; }

		public Func<Dictionary<string, List<MmtToolExEntity>>, bool> ToolDataMonitorHandler { get; set; }

		public virtual void Ini()
		{
			this.HttpPost = new MmtHttpPost
			{
				HostIp = this.AmdHost,
				CertificateName = this.Certificate
			};
			this.HttpPost.Initialize();
			this.ToolDataDal = new ToolDataDal(this.AmdHost, this.DbName, this.DbUser, this.DbPwd);
			this.TdiToolDataDal = new TdiToolDataDal(this.AmdHost, this.DbName, this.DbUser, this.DbPwd);
			this.TdiToolPlaceDal = new TdiToolPlaceDal(this.AmdHost, this.DbName, this.DbUser, this.DbPwd);
			this.TdiToolMasterDataDal = new TdiToolMasterDataDal(this.AmdHost, this.DbName, this.DbUser, this.DbPwd);
			this.TdiToolDataDetailDal = new TdiToolDataDetailsDal(this.AmdHost, this.DbName, this.DbUser, this.DbPwd);
			this.TrgToolDataDetailsDal = new TrgToolDataDetailsDal(this.AmdHost, this.DbName, this.DbUser, this.DbPwd);
		}

        /// <summary>
        /// 监视器
        /// </summary>
        public void StartMonitor()
		{
			if (this._tdRefreshMag == null)
			{
				this._tdRefreshMag = new Thread(new ThreadStart(ToolMagRefresh))
				{
					IsBackground = true
				};
			}
			this._tdRefreshMag.Start();
		}
        /// <summary>
        /// 启动刀具同步
        /// </summary>
        public void StartToolSync()
		{
			if (this._tdToolSync == null)
			{
				this._tdToolSync = new Thread(new ThreadStart(ToolDataSync))
				{
					IsBackground = true
				};
				this._tdToolSync.Start();
			}
		}
		/// <summary>
		/// 刀具同步
		/// </summary>
		private void ToolDataSync()
		{
			List<TrgToolDataDetailsEntity> source = this.TrgToolDataDetailsDal.TrgToolDataMonitor();
			Dictionary<string, List<MmtToolExEntity>> arg = this.QueryToolDataUnion();
			if (this.FirstToolSyncHandler?.Invoke(arg) == true)
			{
				this.TrgToolDataDetailsDal.Clear(source.Select((TrgToolDataDetailsEntity x) => x.Id).ToArray());
			}
			while (true)
			{
				List<TrgToolDataDetailsEntity> list = this.TrgToolDataDetailsDal.TrgToolDataMonitor();
				if (list.Count > 0)
				{
					Dictionary<string, List<MmtToolExEntity>> dictionary = new Dictionary<string, List<MmtToolExEntity>>();
					List<TrgToolDataDetailsEntity> list2 = list.Where((TrgToolDataDetailsEntity x) => x.Operate == "Delete").ToList();
					if (list2.Count > 0)
					{
						dictionary.Add("Delete", list2.Select((TrgToolDataDetailsEntity x) => new MmtToolExEntity
						{
							DbIdTDIToolDataDetails = x.DbIdTDIToolDataDetails
						}).ToList());
					}
					long[] toolDataDetailsPkBuff = (from x in list
						where x.Operate == "Insert" || x.Operate == "Update"
						select x.DbIdTDIToolDataDetails).ToArray();
					Dictionary<string, List<MmtToolExEntity>> dictionary2 = this.QueryToolDataUnion(toolDataDetailsPkBuff);
					List<MmtToolExEntity> list3 = new List<MmtToolExEntity>();
					List<MmtToolExEntity> list4 = new List<MmtToolExEntity>();
					foreach (string key in dictionary2.Keys)
					{
						foreach (MmtToolExEntity entity in dictionary2[key])
						{
							string text = list.FirstOrDefault((TrgToolDataDetailsEntity x) => x.DbIdTDIToolDataDetails == entity.DbIdTDIToolDataDetails)?.Operate;
							if (text == null)
							{
								continue;
							}
							string text2 = text;
							string text3 = text2;
							if (!(text3 == "Insert"))
							{
								if (text3 == "Update")
								{
									list4.Add(entity);
								}
							}
							else
							{
								list3.Add(entity);
							}
						}
					}
					if (list3.Count > 0)
					{
						dictionary.Add("Insert", list3);
					}
					if (list4.Count > 0)
					{
						dictionary.Add("Update", list4);
					}
					if (this.ToolDataMonitorHandler?.Invoke(dictionary) == true)
					{
						this.TrgToolDataDetailsDal.Clear(list.Select((TrgToolDataDetailsEntity x) => x.Id).ToArray());
					}
				}
				Thread.Sleep(300);
			}
		}

		public string GetContainnerId(string deviceNo, int magNo)
		{
			return this.MagConfig.FirstOrDefault((ToolMagConfigEntity x) => x.DeviceNo == deviceNo && x.MagNo == magNo)?.GlobalId;
		}

		public List<ToolPlaceExEntity> QueryAllPlace(string deviceNo, bool? isEmpty = null)
		{
			if (deviceNo == null)
			{
				throw new ArgumentNullException("deviceNo");
			}
			string[] containnerId = (from x in this.MagConfig
				where x.DeviceNo == deviceNo
				select x.GlobalId).ToArray();
			return this.QueryAllPlace(isEmpty, containnerId);
		}

		public List<ToolPlaceExEntity> QueryAllPlace(bool? isEmpty = null, params string[] containnerId)
		{
			if (this.MagConfig == null)
			{
				throw new Exception("缺少刀库配置信息!");
			}
			Dictionary<string, List<ToolPlaceExEntity>> dictionary = new Dictionary<string, List<ToolPlaceExEntity>>();
			List<ToolPlaceEntity> list = this.TdiToolPlaceDal.QueryAllPlace(isEmpty, containnerId);
			List<ToolPlaceExEntity> list2 = new List<ToolPlaceExEntity>();
			foreach (ToolPlaceEntity entity in list)
			{
				ToolMagConfigEntity toolMagConfigEntity = this.MagConfig.FirstOrDefault((ToolMagConfigEntity x) => x.GlobalId.ToUpper() == entity.ContainerId.ToString().ToUpper());
				if (toolMagConfigEntity != null)
				{
					ToolPlaceExEntity toolPlaceExEntity = DataConverter.DeepCopy<ToolPlaceEntity, ToolPlaceExEntity>(entity);
					toolPlaceExEntity.IsEmpty = toolPlaceExEntity.DbIdTDIToolData == 0;
					toolPlaceExEntity.MagName = toolMagConfigEntity.MagName;
					toolPlaceExEntity.MagDescribe = toolMagConfigEntity.MagDescribe;
					toolPlaceExEntity.DeviceNo = toolMagConfigEntity.DeviceNo;
					list2.Add(toolPlaceExEntity);
				}
			}
			return list2;
		}

		public Dictionary<string, List<MmtToolExEntity>> QueryToolDataUnion(long[] toolDataDetailsPkBuff = null)
		{
			if (this.MagConfig == null)
			{
				throw new Exception("缺少刀库配置信息!");
			}
			Dictionary<string, List<MmtToolExEntity>> dictionary = new Dictionary<string, List<MmtToolExEntity>>();
			List<ToolDataUnionEntity> list = this.TdiToolDataDal.QueryToolDataUnion(toolDataDetailsPkBuff);
			List<MmtToolExEntity> list2 = new List<MmtToolExEntity>();
			foreach (ToolDataUnionEntity item in list)
			{
				ToolMagConfigEntity toolMagConfigEntity = this.MagConfig.FirstOrDefault((ToolMagConfigEntity x) => x.GlobalId.ToUpper() == item.ContainerId.ToString().ToUpper());
				if (toolMagConfigEntity == null)
				{
					continue;
				}
				string deviceNo = toolMagConfigEntity.DeviceNo;
				if (item.DbIdTDIToolDataDetails == 0L && item.ToolData == null)
				{
					list2.Add(new MmtToolExEntity
					{
						DbIdTDIToolPlace = item.DbIdTDIToolPlace,
						DbIdTDIToolDataDetails = item.DbIdTDIToolDataDetails,
						DbIdTDIToolData = item.DbIdTDIToolData,
						DeviceNo = deviceNo,
						ContainerId = toolMagConfigEntity.GlobalId,
						MagName = toolMagConfigEntity.MagName,
						ToolInMag = toolMagConfigEntity.MagNo,
						ToolInPlace = ((item.PlaceNo >= 0) ? item.PlaceNo : 0),
						PlaceState = item.PlaceState,
						IsEmpty = true
					});
					continue;
				}
				ToolDataJsonEntity toolDataJsonEntity = JsonConvert.DeserializeObject<ToolDataJsonEntity>(item.ToolData);
				foreach (ToolEdgeEntity eDGE in toolDataJsonEntity.Tool.EDGES)
				{
					MmtToolExEntity mmtToolExEntity = new MmtToolExEntity
					{
						DbIdTDIToolPlace = item.DbIdTDIToolPlace,
						DbIdTDIToolDataDetails = item.DbIdTDIToolDataDetails,
						DbIdTDIToolData = item.DbIdTDIToolData,
						DeviceNo = deviceNo,
						ContainerId = toolMagConfigEntity.GlobalId,
						MagName = toolMagConfigEntity.MagName,
						ToolInMag = toolMagConfigEntity.MagNo,
						UserData = JsonConvert.SerializeObject(toolDataJsonEntity.Tool.TC_TPC)
					};
					mmtToolExEntity.ToolInMag = toolDataJsonEntity.Tool.TC_TP.A_TOOLMN;
					mmtToolExEntity.ToolIdent = toolDataJsonEntity.Tool.TC_TP.TC_TP2;
					mmtToolExEntity.ToolInPlace = ((item.PlaceNo >= 0) ? item.PlaceNo : 0);
					mmtToolExEntity.DuploNo = toolDataJsonEntity.Tool.TC_TP.TC_TP1;
					mmtToolExEntity.NumCuttEdges = toolDataJsonEntity.Tool.EDGES.Count;
					mmtToolExEntity.ToolState = item.ToolState;
					mmtToolExEntity.ToolMon = item.ToolMonitorType;
					mmtToolExEntity.PlaceState = item.PlaceState;
					mmtToolExEntity.LeftSize = item.ToolSizeLeft;
					mmtToolExEntity.RightSize = item.ToolSizeRight;
					mmtToolExEntity.TopSize = item.ToolSizeTop;
					mmtToolExEntity.BottomSize = item.ToolSizeDown;
					mmtToolExEntity.WorkCountSet = eDGE.TC_MOP.TC_MOP13;
					mmtToolExEntity.WorkCountRemain = eDGE.TC_MOP.TC_MOP4;
					mmtToolExEntity.WorkCountLimit = eDGE.TC_MOP.TC_MOP3;
					mmtToolExEntity.LifeQualitySet = eDGE.TC_MOP.TC_MOP11;
					mmtToolExEntity.LifeQualityRemain = eDGE.TC_MOP.TC_MOP2;
					mmtToolExEntity.LifeLimit = eDGE.TC_MOP.TC_MOP1;
					mmtToolExEntity.EdgeWearActual = eDGE.TC_MOP.TC_MOP5;
					mmtToolExEntity.EdgeWearLimit = eDGE.TC_MOP.TC_MOP6;
					mmtToolExEntity.EdgeWearSet = eDGE.TC_MOP.TC_MOP15;
					mmtToolExEntity.WearLength = eDGE.TC_DP.TC_DP12;
					mmtToolExEntity.WearLength1 = eDGE.TC_DP.TC_DP13;
					mmtToolExEntity.CornerRadius = eDGE.TC_DP.TC_DP7;
					mmtToolExEntity.Radius1 = eDGE.TC_DP.TC_DP6;
					mmtToolExEntity.Length1 = eDGE.TC_DP.TC_DP3;
					mmtToolExEntity.EdgePosition = eDGE.TC_DP.TC_DP2;
					mmtToolExEntity.ToolType = item.ToolType;
					mmtToolExEntity.DNo = eDGE.EDGE;
					mmtToolExEntity.ToolNo = item.ToolTno;
					mmtToolExEntity.WearRadius1 = eDGE.TC_DP.TC_DP15;
					mmtToolExEntity.TimeStamp = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
					byte[] bytes = BitConverter.GetBytes(item.PlaceState);
					bool[] array = EnDeCode.ByteToBoolArray(bytes, bytes.Length);
					list2.Add(mmtToolExEntity);
				}
			}
			if (list2.Count > 0)
			{
				IEnumerable<IGrouping<string, MmtToolExEntity>> enumerable = from x in list2
					group x by x.DeviceNo;
				foreach (IGrouping<string, MmtToolExEntity> item2 in enumerable)
				{
					string key = item2.Key;
					dictionary.Add(key, item2.ToList());
				}
			}
			return dictionary;
		}

		public void ToolMagRefresh()
		{
			try
			{
				while (true)
				{
					try
					{
						Tuple<bool, string, List<BaseMmtToolEntity>, List<string>, string> tuple = this.HttpPost.QueryToolEntites(this.DeviceNode, this.DstMag);
						this.RefreshSucess = tuple.Item1;
						this.RefreshResponse = tuple.Item2;
						List<MmtToolEntity> list = tuple.Item3.Select((BaseMmtToolEntity x) => x as MmtToolEntity).ToList();
						this.ToolMagEntites = (this.RefreshSucess ? list : new List<MmtToolEntity>());
						this.EmptyPlaces = (this.RefreshSucess ? tuple.Item4 : new List<string>());
						Thread.Sleep(500);
					}
					catch (Exception ex)
					{
						this.RefreshResponse = ex.ToString();
					}
				}
			}
			catch (Exception ex2)
			{
				throw ex2;
			}
		}

		public virtual Tuple<bool, string, string> Load(MmtToolEntity entity, int dstPlace, string userDataFormat, UserDataEntity userDataEntity, bool saveOriUserData = true, bool autoExternId = true)
		{
			Tuple<bool, string> tuple = this.HttpPost.CreateMasterData(entity.ToolIdentify, entity.DuploNo, entity.ToolType, userDataEntity);
			if (!tuple.Item1)
			{
				this.LoadToolHandler?.Invoke(arg1: false, tuple.Item2);
				return new Tuple<bool, string, string>(item1: false, tuple.Item2, "");
			}
			if (!string.IsNullOrEmpty(userDataFormat) && saveOriUserData)
			{
				Tuple<bool, string, List<BaseMmtToolEntity>, List<string>, string> tuple2 = this.HttpPost.QueryToolEntites(this.ServerNode, this.TrashMag);
				if (!tuple2.Item1)
				{
					this.LoadToolHandler?.Invoke(arg1: false, tuple2.Item2);
					return new Tuple<bool, string, string>(item1: false, tuple2.Item2, "");
				}
				MmtToolEntity mmtToolEntity = (MmtToolEntity)tuple2.Item3.LastOrDefault((BaseMmtToolEntity x) => x.ToolIdentify == entity.ToolIdentify);
				if (mmtToolEntity != null)
				{
					userDataEntity.TC_TPC1 = mmtToolEntity.TC_TPC1;
					userDataEntity.TC_TPC2 = mmtToolEntity.TC_TPC2;
					userDataEntity.TC_TPC3 = mmtToolEntity.TC_TPC3;
					userDataEntity.TC_TPC4 = mmtToolEntity.TC_TPC4;
					userDataEntity.TC_TPC5 = mmtToolEntity.TC_TPC5;
					userDataEntity.TC_TPC6 = mmtToolEntity.TC_TPC6;
					userDataEntity.TC_TPC7 = mmtToolEntity.TC_TPC7;
					userDataEntity.TC_TPC8 = mmtToolEntity.TC_TPC8;
					userDataEntity.TC_TPC9 = mmtToolEntity.TC_TPC9;
					userDataEntity.TC_TPC10 = mmtToolEntity.TC_TPC10;
				}
			}
			if (!string.IsNullOrEmpty(userDataFormat) && !this.TdiToolMasterDataDal.InsertUserData(entity.ToolIdentify, entity.ToolType, userDataFormat, userDataEntity))
			{
				this.LoadToolHandler?.Invoke(arg1: false, "创建用户数据失败！");
				return new Tuple<bool, string, string>(item1: false, "创建用户数据失败！", "");
			}
			if (string.IsNullOrEmpty(entity.TDI_EXTERN_ID) && autoExternId)
			{
				entity.TDI_EXTERN_ID = Guid.NewGuid().ToString();
			}
			Tuple<bool, string> tuple3 = this.HttpPost.ImportTool(this.ServerNode, this.PresetterMag, entity);
			if (!tuple3.Item1)
			{
				this.LoadToolHandler?.Invoke(arg1: false, tuple3.Item2);
				return new Tuple<bool, string, string>(item1: false, tuple3.Item2, "");
			}
			int sumTime = 0;
			TDI_TOOLDATAEntity tDI_TOOLDATAEntity = this.CheckInsert(entity.TDI_EXTERN_ID, ref sumTime, 500);
			if (tDI_TOOLDATAEntity == null)
			{
				this.LoadToolHandler?.Invoke(arg1: false, "检测Presetter数据超时");
				return new Tuple<bool, string, string>(item1: false, "检测Presetter数据超时", "");
			}
			Tuple<TDI_TOOLDATA_DETAILSEntity, TDI_TOOLPLACEEntity> tuple4 = this.TdiToolDataDetailDal.UpdateUserData(this.ServerNode, this.PresetterMag, userDataFormat, tDI_TOOLDATAEntity.DbIdTDIToolData);
			if (tuple4.Item2 == null)
			{
				this.LoadToolHandler?.Invoke(arg1: false, "未检测到插入数据的位置信息！");
				return new Tuple<bool, string, string>(item1: false, "未检测到插入数据的位置信息！", "");
			}
			Tuple<bool, string, string, string> tuple5 = this.HttpPost.LoadUnload(this.ServerNode, this.PresetterMag, tuple4.Item2.PlaceNo, this.DeviceNode, this.DstMag, entity.ToolIdentify, dstPlace);
			if (!tuple5.Item1)
			{
				this.LoadToolHandler?.Invoke(arg1: false, tuple5.Item2);
				return new Tuple<bool, string, string>(item1: false, tuple5.Item2, "");
			}
			DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(26, 3);
			defaultInterpolatedStringHandler.AppendLiteral("发送成功请准备实时进行监控！刀具:");
			defaultInterpolatedStringHandler.AppendFormatted(entity.ToolIdentify);
			defaultInterpolatedStringHandler.AppendLiteral("DuploNo:");
			defaultInterpolatedStringHandler.AppendFormatted(entity.DuploNo);
			defaultInterpolatedStringHandler.AppendLiteral("-");
			defaultInterpolatedStringHandler.AppendFormatted(DateTime.Now);
			return new Tuple<bool, string, string>(item1: true, defaultInterpolatedStringHandler.ToStringAndClear(), tuple5.Item4);
		}

		public virtual Tuple<bool, string, string> UnLoad(MmtToolEntity entity, bool clearTrah = false)
		{
			Tuple<bool, string, string, string> tuple = this.HttpPost.LoadUnload(this.DeviceNode, this.DstMag, entity.MagPlace, this.ServerNode, this.TrashMag, entity.ToolIdentify, 0);
			if (!tuple.Item1)
			{
				return new Tuple<bool, string, string>(item1: false, tuple.Item2, "");
			}
			if (clearTrah)
			{
				Tuple<bool, string> tuple2 = this.ClearTrashMag();
				if (!tuple2.Item1)
				{
					return new Tuple<bool, string, string>(item1: false, tuple2.Item2, "");
				}
			}
			DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(17, 3);
			defaultInterpolatedStringHandler.AppendLiteral("操作成功！刀具:");
			defaultInterpolatedStringHandler.AppendFormatted(entity.ToolIdentify);
			defaultInterpolatedStringHandler.AppendLiteral("DuploNo:");
			defaultInterpolatedStringHandler.AppendFormatted(entity.DuploNo);
			defaultInterpolatedStringHandler.AppendLiteral("-");
			defaultInterpolatedStringHandler.AppendFormatted(DateTime.Now);
			return new Tuple<bool, string, string>(item1: true, defaultInterpolatedStringHandler.ToStringAndClear(), tuple.Item4);
		}

		public void AsyncGetSendBack(string guid)
		{
			if (this._tdGetSendBack != null)
			{
				this._getSendBackAbort = false;
				this.GetSendBackHandler?.Invoke("实时监听刀具装/卸载任务正在进行！");
				return;
			}
			this._getSendBackAbort = true;
			this._tdGetSendBack = new Thread((ThreadStart)delegate
			{
				while (this._getSendBackAbort)
				{
					try
					{
						Tuple<string, string> tuple = this.HttpPost.SendGetRequests(guid);
						this.GetSendBackHandler?.Invoke(tuple.Item2);
						if (!this.HttpPost.AbortTd(tuple.Item1))
						{
							Thread.Sleep(100);
							continue;
						}
					}
					catch (Exception ex)
					{
						throw ex;
					}
					break;
				}
				this._tdGetSendBack = null;
			})
			{
				IsBackground = true
			};
			this._tdGetSendBack.Start();
		}

		public Tuple<bool, string> SyncGetSendBack(string guid, int timeOut = 3000)
		{
			double num = 0.0;
			Stopwatch stopwatch = new Stopwatch();
			while (true)
			{
				try
				{
					stopwatch.Reset();
					stopwatch.Start();
					Tuple<string, string> tuple = this.HttpPost.SendGetRequests(guid);
					this.GetSendBackHandler?.Invoke(tuple.Item2);
					Thread.Sleep(100);
					stopwatch.Stop();
					if (tuple.Item1 == "HS_UNLOAD_STARTED" || tuple.Item1 == "HS_LOAD_STARTED")
					{
						return new Tuple<bool, string>(item1: true, "Success");
					}
					if (tuple.Item1 == "Error")
					{
						return new Tuple<bool, string>(item1: false, "Error");
					}
					num += (double)stopwatch.ElapsedMilliseconds;
					if (num >= (double)timeOut)
					{
						return new Tuple<bool, string>(item1: false, "Request Timeout");
					}
				}
				catch (Exception ex)
				{
					throw ex;
				}
			}
		}

		protected TDI_TOOLDATAEntity CheckInsert(string externId, ref int sumTime, int timeOut)
		{
			TDI_TOOLDATAEntity tDI_TOOLDATAEntity = this.TdiToolDataDal.QueryTdiToolData(externId);
			int num = 30;
			if (tDI_TOOLDATAEntity == null)
			{
				Thread.Sleep(num);
				if (sumTime >= timeOut)
				{
					return null;
				}
				sumTime += num;
				TDI_TOOLDATAEntity tDI_TOOLDATAEntity2 = this.CheckInsert(externId, ref sumTime, timeOut);
				if (tDI_TOOLDATAEntity2 != null)
				{
					return tDI_TOOLDATAEntity2;
				}
			}
			return tDI_TOOLDATAEntity;
		}

		public virtual Tuple<bool, string> ClearPresetterMag(bool isClearTrash = true)
		{
			Tuple<bool, string, List<BaseMmtToolEntity>, List<string>, string> tuple = this.HttpPost.QueryToolEntites(this.ServerNode, this.PresetterMag);
			if (!tuple.Item1)
			{
				this.DeleteToolHandler?.Invoke(arg1: false, tuple.Item2);
				return new Tuple<bool, string>(item1: false, tuple.Item2);
			}
			if (tuple.Item3.Count == 0)
			{
				return new Tuple<bool, string>(item1: true, "");
			}
			DefaultInterpolatedStringHandler defaultInterpolatedStringHandler;
			foreach (BaseMmtToolEntity item in tuple.Item3)
			{
				MmtToolEntity mmtToolEntity = (MmtToolEntity)item;
				Tuple<bool, string, string, string> tuple2 = this.HttpPost.LoadUnload(this.ServerNode, this.PresetterMag, mmtToolEntity.MagPlace, this.ServerNode, this.TrashMag, mmtToolEntity.ToolIdentify, 0);
				if (!tuple2.Item1)
				{
					defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(23, 2);
					defaultInterpolatedStringHandler.AppendLiteral("操作中断！移除目标刀具:");
					defaultInterpolatedStringHandler.AppendFormatted(mmtToolEntity.ToolIdentify);
					defaultInterpolatedStringHandler.AppendLiteral("DuploNo:");
					defaultInterpolatedStringHandler.AppendFormatted(mmtToolEntity.DuploNo);
					defaultInterpolatedStringHandler.AppendLiteral("失败！");
					string text = defaultInterpolatedStringHandler.ToStringAndClear();
					this.DeleteToolHandler?.Invoke(arg1: false, text);
					return new Tuple<bool, string>(item1: false, text);
				}
			}
			if (isClearTrash)
			{
				Tuple<bool, string> tuple3 = this.ClearTrashMag();
				if (!tuple3.Item1)
				{
					this.DeleteToolHandler?.Invoke(arg1: false, tuple3.Item2);
					return new Tuple<bool, string>(item1: false, tuple3.Item2);
				}
			}
			defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(10, 1);
			defaultInterpolatedStringHandler.AppendLiteral("清空成功！受影响数量");
			defaultInterpolatedStringHandler.AppendFormatted(tuple.Item3.Count);
			return new Tuple<bool, string>(item1: true, defaultInterpolatedStringHandler.ToStringAndClear());
		}

		public virtual Tuple<bool, string> ClearTrashMag()
		{
			Tuple<bool, string, List<BaseMmtToolEntity>, List<string>, string> tuple = this.HttpPost.QueryToolEntites(this.ServerNode, this.TrashMag);
			if (!tuple.Item1)
			{
				return new Tuple<bool, string>(item1: false, tuple.Item2);
			}
			if (tuple.Item3.Count == 0)
			{
				return new Tuple<bool, string>(item1: true, "");
			}
			List<int> toolLocList = new List<int>();
			tuple.Item3.ForEach(delegate(BaseMmtToolEntity x)
			{
				if (!toolLocList.Contains(x.MagPlace))
				{
					toolLocList.Add(x.MagPlace);
				}
			});
			return this.HttpPost.DeleteTools(this.ServerNode, this.TrashMag, toolLocList);
		}

		public virtual Tuple<bool, string> DeleteTools(List<int> toolLocList)
		{
			return this.HttpPost.DeleteTools(this.ServerNode, this.TrashMag, toolLocList);
		}

		public Tuple<bool, string> ClearMasterDatas()
		{
			Tuple<bool, string, List<string>> tuple = this.HttpPost.QueryMasterData();
			if (!tuple.Item1)
			{
				return new Tuple<bool, string>(item1: false, tuple.Item2);
			}
			foreach (string item in tuple.Item3)
			{
				Tuple<bool, string> tuple2 = this.HttpPost.DeleteMasterData(item);
				if (!tuple2.Item1)
				{
					return new Tuple<bool, string>(item1: false, tuple2.Item2);
				}
			}
			return new Tuple<bool, string>(item1: true, "");
		}
	}
}
